<?php
class IndexController extends Controller{
	public function index(){
		$this->assign('inject', '');
		$this->display('login/index.tpl');
	}
	public function login(){
		global $_POST;
		error_reporting(0);
		$username = isset($_POST['username']) ? $_POST['username'] : '';
		$password = isset($_POST['password']) ? $_POST['password'] : '';
		$code = isset($_POST['code']) ? $_POST['code'] : '';
		$check = isset($_POST['check']) && $_POST['check'] == 'true' ? true : false;
		//检查验证码
		if(empty($code)){
			exit(json_encode(array(
				'state' => -1,
				'info' => '验证码不能为空'
			)));
		}
		if(!Authhelper::check_validate($code)){
			exit(json_encode(array(
				'state' => -2,
				'info' => '验证码不正确'
			)));
		}
		//有效性检查
		if(empty($username)){
			exit(json_encode(array(
				'state' => -3,
				'info' => '用户名不能为空'
			)));
		}
		if(empty($password)){
			exit(json_encode(array(
				'state' => -4,
				'info' => '密码不能为空'
			)));
		}
		//检查用户
		list($uid, $username, $password, $email) = uc_user_login($_POST['username'], $_POST['password']);
		if($uid < 0) {
			if($uid == -1) {
				exit(json_encode(array(
					'state' => -5,
					'info' =>'用户不存在，或者已经被删除'
				)));
			}
			if($uid == -2){
				exit(json_encode(array(
					'state' => -6,
					'info' =>'密码不正确'
				)));
			}
			if($uid == -3){
				exit(json_encode(array(
					'state' => -7,
					'info'=> '未知错误'
				)));
			}
		}
		//验证成功
		//是否记住用户
		if($check){
			Authhelper::s_login($uid, $username, $password);
		}
		//将同步登陆代码注入到页面中
		$inject = uc_user_synlogin($uid);
		exit(json_encode(array(
			'state' => 1,
			'info'=> '登陆成功,即将跳转到指定页面'.$inject
		)));
	}
	public function logout(){
		Authhelper::logout();
		$inject = '你已成功登出'.uc_user_synlogout();
		$this->assign('inject', $inject);
		$this->display('login/index.tpl');
	}
	public function validate(){
		$_vd = new Validate();
		$_vd->doimg();
		$code = $_vd->getCode();
		Authhelper::save_validate($code);
	}
}